import Qs from 'qs'
import md5 from 'js-md5'

export const HEADER_APPID = 'App-Auth-appid'
export const HEADER_REQURL = 'App-Auth-reqUrl'
export const HEADER_TIMESTAMP = 'App-Auth-timestamp'
export const HEADER_NONCESTR = 'App-Auth-nonceStr'
export const HEADER_SIGN = 'App-Auth-sign'
export const APPID = 'htappid'
const APPSECRET = 'appsecret'
export const APP_AUTH_ENABLE = true

export const generateSignJson = (reqUrl, timestamp, nonceStr, data) => {
  const params = {
    'appid': APPID,
    'nonceStr': nonceStr,
    'timestamp': timestamp,
    'reqUrl': reqUrl,
    'postJsonStr': JSON.stringify(data)
  }
  return md5.hex(generateStringFromJsonObj(params) + APPSECRET).toUpperCase()
}

export const generateSignQs = (reqUrl, timestamp, nonceStr, data) => {
  const params = {
    'appid': APPID,
    'nonceStr': nonceStr,
    'timestamp': timestamp,
    'reqUrl': reqUrl
  }
  for (const key in data) {
    params[key] = data[key]
  }
  return md5.hex(generateStringFromJsonObj(params) + APPSECRET).toUpperCase()
}

export const generateSignGet = (reqUrl, timestamp, nonceStr) => {
  const params = {
    'appid': APPID,
    'nonceStr': nonceStr,
    'timestamp': timestamp,
    'reqUrl': reqUrl
  }
  if (reqUrl.indexOf('?') > 0) {
    const urlAndQueryString = reqUrl.split('?')
    params.reqUrl = urlAndQueryString[0]
    const queryString = urlAndQueryString[1]
    if (queryString) {
      // Qs.parse(queryString)，对c=c&a=a&a=b&b=b这样的字符串，最后parse后得到是a: ['a', 'b']
      const qStrJsonObj = Qs.parse(queryString)
      for (const key in qStrJsonObj) {
        params[key] = qStrJsonObj[key]
      }
    }
  }
  return md5.hex(generateStringFromJsonObj(params) + APPSECRET).toUpperCase()
}

/**
 * 从JSON对象中获取请求需要加密的字符串
 * 如果是
 *  {
 *      a: ['a','b']
 *  }
 * 的数组形式，则转化后为a=a,b，后台对应的也应该是a=a,b的形式
 * @param {*} jsonObj
 */
export const generateStringFromJsonObj = (jsonObj) => {
  const keys = []
  for (const key in jsonObj) {
    keys.push(key)
  }
  keys.sort()
  let string = ''
  keys.forEach(key => {
    if (jsonObj[key] && (jsonObj[key] + '').trim()) {
      if (string === '') {
        string = string + key + '=' + jsonObj[key]
      } else {
        string = string + '&' + key + '=' + jsonObj[key]
      }
    }
  })
  return string
}
